﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using KL.Store.Web.Models;
using KL.Store.Data;
using KL.Store.Core;
using KL.Store.Core.Domain;
using TN.Web.Utils;
using CaptchaMvc.HtmlHelpers;
using CaptchaMvc.Attributes;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace KL.Store.Web.Controllers
{

    [RequireHttps]
    [Authorize]
    public class AccountController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index(string returnUrl)
        {
          
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        #endregion

        #region Login
        
        [AllowAnonymous]
        public ActionResult LoginRedirect(string returnUrl, int? id)
        {
            if (returnUrl == "/Cart/Update" || returnUrl == "/Cart/Remove" || returnUrl == "/Cart/Insert" || returnUrl == "/Cart/RemoveAll" || returnUrl == "/WishList/List")
            {
                returnUrl = "";
            }
            else if (returnUrl == "/Cart/Refresh")
            {
                returnUrl = "/Cart/CheckOut";
            }
            else if (returnUrl == "/Contact/ListGet")
            {
                returnUrl = "/Contact/List";
            }

            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
         
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (dbAccount.CheckPassword(model.UserName, model.Password) == true)
                {
                    int productToAddCart = eStoreUser.ProductIdToAddCart;
                    string productVariantToAddCart = eStoreUser.ProductVariantToAddCart;
                    bool installmentSelected = eStoreUser.InstallmentSelected;
                    int productAmountToAddCart = eStoreUser.ProductAmountToAddCart;
                    string utmReferral = eStoreUser.UTMReferral ?? "";
                    int VisitorId = eStoreUser.AccountId;

                    Account account = dbAccount.Get(model.UserName);

                    

                    //FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    FormsAuthentication.SetAuthCookie(model.UserName, true);

                    ActiveAccount activeAccount = new ActiveAccount();

                    activeAccount.AccountId = account.AccountId;
                    activeAccount.UserName = account.Email;
                    activeAccount.FirstName = account.FirstName;
                    activeAccount.LastName = account.LastName;
                    activeAccount.Email = account.Email;
                    activeAccount.Mobile = account.Mobile;
                    activeAccount.UTMReferral = utmReferral.ToUpperInvariant();
                    activeAccount.BasketLocked = account.BasketLocked;
                    activeAccount.IsManager = account.IsManager;
                    activeAccount.IsSeoManager = account.IsSeoManager;
                    activeAccount.IsReportManager = account.IsReportManager;
                    activeAccount.IsAllowedBuyPrice = account.IsAllowedBuyPrice;
                    activeAccount.AccountType = 0;

                    if (productToAddCart > 0)
                    {
                        if (Parameters.AllowVisitorsToUsingCart)
                        {
                            dbCart.VisitorToUser(VisitorId, activeAccount.AccountId);
                            dbAddress.VisitorToUser(VisitorId, activeAccount.AccountId);
                        }
                        else
                        {
                            dbCart.Insert(activeAccount.AccountId, 0, 0, productToAddCart, productAmountToAddCart, 0, false, installmentSelected, Parameters.Now, productVariantToAddCart, activeAccount.AccountType);
                        }
                    }

                    #region Cart Summary

                    CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                    activeAccount.TotalQty = summary.TotalQty;
                    activeAccount.TotalPrice = summary.TotalPrice;
                    activeAccount.InstallmentPrice = summary.InstallmentPrice;
                    activeAccount.InstallmentTax = summary.InstallmentTax;

                    #endregion

                    activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                    #region Related Lists

                    //activeAccount.RelatedLists = dbWishLists.GetUserRelatedLists(activeAccount.AccountId);

                    #endregion

                    ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();
                    if (string.IsNullOrEmpty((activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd()))
                    {
                        //var aa = 1;
                    }
                    // session log için eklendi
                    dbAccount.InsertLog(account.AccountId, ViewData["StoreUserName"].ToString());

                    Session["eStoreUser"] = activeAccount;

                    if (!string.IsNullOrEmpty(activeAccount.RedirectUrl))
                    {
                        return Redirect(activeAccount.RedirectUrl);
                    }
                    else
                    {
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            //return RedirectToAction("Index", "Home");
                            return Redirect(Parameters.WebSiteUrl + "/Home/Index");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Eposta adresi yada şifre hatalı.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult LoginPartial(string returnUrl)
        {
           
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
         
        [AllowAnonymous]
        [HttpPost]
        public ActionResult LoginPartial(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (dbAccount.CheckPassword(model.UserName, model.Password) == true)
                {
                    int productToAddCart = eStoreUser.ProductIdToAddCart;
                    string productVariantToAddCart = eStoreUser.ProductVariantToAddCart;
                    bool installmentSelected = eStoreUser.InstallmentSelected;
                    int productAmountToAddCart = eStoreUser.ProductAmountToAddCart;
                    string utmReferral = eStoreUser.UTMReferral ?? "";
                    int VisitorId = eStoreUser.AccountId;

                    Account account = dbAccount.Get(model.UserName);

                    //FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    FormsAuthentication.SetAuthCookie(model.UserName, true);

                    

                    ActiveAccount activeAccount = new ActiveAccount();

                    activeAccount.AccountId = account.AccountId;
                    activeAccount.UserName = account.Email;
                    activeAccount.FirstName = account.FirstName;
                    activeAccount.LastName = account.LastName;
                    activeAccount.Email = account.Email;
                    activeAccount.Mobile = account.Mobile;
                    activeAccount.UTMReferral = utmReferral.ToUpperInvariant();
                    activeAccount.BasketLocked = account.BasketLocked;
                    activeAccount.IsManager = account.IsManager;
                    activeAccount.IsSeoManager = account.IsSeoManager;
                    activeAccount.IsReportManager = account.IsReportManager;
                    activeAccount.IsAllowedBuyPrice = account.IsAllowedBuyPrice;
                    activeAccount.AccountType = 0;

                    if (productToAddCart > 0)
                    {
                        if (Parameters.AllowVisitorsToUsingCart)
                        {
                            dbCart.VisitorToUser(VisitorId, activeAccount.AccountId);
                            dbAddress.VisitorToUser(VisitorId, activeAccount.AccountId);
                        }
                        else
                        {
                            dbCart.Insert(activeAccount.AccountId, 0, 0, productToAddCart, productAmountToAddCart, 0, false, installmentSelected, Parameters.Now, productVariantToAddCart, activeAccount.AccountType);
                        }
                    }

                    #region Cart Summary

                    CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                    activeAccount.TotalQty = summary.TotalQty;
                    activeAccount.TotalPrice = summary.TotalPrice;
                    activeAccount.InstallmentPrice = summary.InstallmentPrice;
                    activeAccount.InstallmentTax = summary.InstallmentTax;

                    #endregion
                    activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                    #region Related Lists

                    //activeAccount.RelatedLists = dbWishLists.GetUserRelatedLists(activeAccount.AccountId);

                    #endregion

                    ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();
                    Session["eStoreUser"] = activeAccount;

                    dbAccount.InsertLog(account.AccountId, ViewData["StoreUserName"].ToString());

                    if (!string.IsNullOrEmpty(activeAccount.RedirectUrl))
                    {
                        return Redirect(activeAccount.RedirectUrl);
                      //  return Json(new { url = activeAccount.RedirectUrl });
                    }
                    else
                    {
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                            //return Json(new { url = returnUrl });
                        }
                        else
                        {
                            return Redirect(Parameters.WebSiteUrl + "/Home/Index");
                            //return Json(new { url = Parameters.WebSiteUrl + "/Home/Index" });
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Eposta adresi yada şifre hatalı.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


        #region FacebookPartial

        [AllowAnonymous]
        public ActionResult FacebookLoginPartial()
        {
            return View();
        }

        #endregion

        #endregion

        #region Logoff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        #endregion

        #region Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            

            RegisterModel model = new RegisterModel();
            model.CityList = dbCity.GetList(1);
            model.CampaingSMSAndEmail = true;
            model.NewsLetter = true;
            return View(model);
        }

        [AllowAnonymous]
        //[CaptchaVerify("Hatalı Kod")]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            #region CaptchaVerify
            if (Parameters.UseCaptchaOnRegister && !this.IsCaptchaVerify("Hatalı Doğrulama Kodu."))
            {
                ModelState.AddModelError("", "Hatalı Doğrulama Kodu.");
                return View();
            }

            #endregion

            #region AgreePrivacyPolicy Control

            //if (model.AgreePrivacyPolicy != true)
            //{
            //    ModelState.AddModelError("AgreePrivacyPolicy", "Lütfen üyelik sözleşmesini onaylayınız.");
            //}

            #endregion

            #region Birthday Control

            if (model.SetBirthDate != null && model.SetBirthDate.Day > 0 && model.SetBirthDate.Month > 0 && model.SetBirthDate.Year > 0)
            {
                try
                {
                    model.BirthDay = new DateTime(model.SetBirthDate.Year, model.SetBirthDate.Month, model.SetBirthDate.Day);
                }
                catch
                {
                    ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
                }

            }
            else if (model.SetBirthDate != null && (model.SetBirthDate.Day > 0 || model.SetBirthDate.Month > 0 || model.SetBirthDate.Year > 0))
            {
                ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
            }

            else
            {
                model.BirthDay = new DateTime(1900, 1, 1);
            }

            #endregion

            if (ModelState.IsValid)
            {
                var utmRefferal = "";
                //int id = (int)dbAccount.Insert(model.FirstName, model.LastName, model.Email, model.BirthDay, model.Address1, model.Address2, model.Address3, model.Address4, model.City, model.Phone, model.Mobile, model.Fax, model.PhoneInternational, model.Password, model.NewsLetter == true ? 1 : 0, model.CampaingSMSAndEmail == true ? 1 : 0);
                if (!string.IsNullOrEmpty(eStoreUser.UTMReferral))
                {
                    if (eStoreUser.UTMReferral == "akakce")
                    {
                        utmRefferal = "AA";
                    }
                    else if (eStoreUser.UTMReferral == "gittigidiyor")
                    {
                        utmRefferal = "GG";
                    }
                    else if (eStoreUser.UTMReferral == "cimri")
                    {
                        utmRefferal = "Cİ";
                    }
                    else if (eStoreUser.UTMReferral == "google")
                    {
                        utmRefferal = "GO";
                    }
                    else
                    {
                        utmRefferal = "";
                    }
                }

                int id = (int)dbAccount.Insert(model.FirstName, model.LastName, model.Email, model.BirthDay, "", "", "", "", 0, "", model.Mobile, "", "", model.Password, model.NewsLetter == true ? 1 : 0, model.CampaingSMSAndEmail == true ? 1 : 0, Parameters.Now, utmRefferal);

                if (id > 0)
                {
                    int productToAddCart = eStoreUser.ProductIdToAddCart;
                    string productVariantToAddCart = eStoreUser.ProductVariantToAddCart;
                    bool installmentSelected = eStoreUser.InstallmentSelected;
                    int productAmountToAddCart = eStoreUser.ProductAmountToAddCart;
                    string utmReferral = eStoreUser.UTMReferral ?? "";
                    int VisitorId = eStoreUser.AccountId;

                    //dbAddress.Insert(id, "Adresim", "", "", "", model.Address1, model.Address2, model.Address3, model.Address4, 1, model.City, id);
                    //dbAddress.Insert(id, "Fatura Adresim", "", "", "", model.Address1, model.Address2, model.Address3, model.Address4, 1, model.City, id);

                    Account account = dbAccount.Get(model.Email);

                    FormsAuthentication.SetAuthCookie(model.Email, false);

                    ActiveAccount activeAccount = new ActiveAccount();

                    activeAccount.AccountId = account.AccountId;
                    activeAccount.UserName = account.Email;
                    activeAccount.FirstName = account.FirstName;
                    activeAccount.LastName = account.LastName;
                    activeAccount.Email = account.Email;
                    activeAccount.Mobile = account.Mobile;
                    activeAccount.UTMReferral = utmReferral.ToUpperInvariant();
                    activeAccount.AccountType = 0;

                    #region Cart Summary

                    if (productToAddCart > 0)
                    {

                        if (Parameters.AllowVisitorsToUsingCart)
                        {
                            dbCart.VisitorToUser(VisitorId, activeAccount.AccountId);
                            dbAddress.VisitorToUser(VisitorId, activeAccount.AccountId);
                        }
                        else
                        {
                            dbCart.Insert(activeAccount.AccountId, 0, 0, productToAddCart, productAmountToAddCart, 0, false, installmentSelected, Parameters.Now, productVariantToAddCart, activeAccount.AccountType);
                        }
                    }

                    CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                    activeAccount.TotalQty = summary.TotalQty;
                    activeAccount.TotalPrice = summary.TotalPrice;
                    activeAccount.InstallmentPrice = summary.InstallmentPrice;
                    activeAccount.InstallmentTax = summary.InstallmentTax;

                    #endregion
                    activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                    ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();
                    Session["eStoreUser"] = activeAccount;

                    #region Verify Account Mail Send

                    string mailBody = dbRefs.GetRef5(200);
                    string Link = Parameters.WebSiteUrl + "/Account/Verify/?id=" + HttpUtility.UrlEncode(Crypt.Encrypt(activeAccount.Email));

                    Link = "<a href=\"" + Link + "\">" + Link + "</a>";
                    mailBody = mailBody.Replace("{Link}", Link).Replace("{FirstName}", activeAccount.FirstName).Replace("{LastName}", activeAccount.LastName).Replace("{Email}", activeAccount.UserName);

                    try
                    {
                        Utils.SendMail(activeAccount.Email, "", Parameters.NewMemberMailBccAddress, "Yeni Üye", mailBody, true);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }

                    #endregion
                    if (!string.IsNullOrEmpty(activeAccount.RedirectUrl))
                    {
                        return Redirect(activeAccount.RedirectUrl);
                    }
                    else if (productToAddCart > 0)
                    {
                        return Redirect(Parameters.WebSiteUrl + "/Cart/Index");
                    }
                    else if (Parameters.UseWishList)
                    {
                        return Redirect(Parameters.WebSiteUrl + "/Contact/Index");
                    }
                    else
                    {
                        return Redirect(Parameters.WebSiteUrl + "/Home/Index");
                    }
                }
                else if (id == -1)
                {
                    ModelState.AddModelError("", "Sistemimizde Eposta adresi bulunmaktadır.");
                }
            }

            model.CityList = dbCity.GetList(1);
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult RegisterPartial()
        {
           

            RegisterModel model = new RegisterModel();
            model.CityList = dbCity.GetList(1);
            model.CampaingSMSAndEmail = true;
            model.NewsLetter = true;

            return View(model);
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult RegisterPartial(RegisterModel model)
        {

            #region CaptchaVerify
            if (Parameters.UseCaptchaOnRegister && !this.IsCaptchaVerify("Hatalı Doğrulama Kodu."))
            {
                ModelState.AddModelError("", "Hatalı Doğrulama Kodu.");
                return View();
            }

            #endregion

            #region AgreePrivacyPolicy Control

            //if (model.AgreePrivacyPolicy != true)
            //{
            //    ModelState.AddModelError("AgreePrivacyPolicy", "Lütfen üyelik sözleşmesini onaylayınız.");
            //}

            #endregion

            #region Birthday Control

            if (model.SetBirthDate != null && model.SetBirthDate.Day > 0 && model.SetBirthDate.Month > 0 && model.SetBirthDate.Year > 0)
            {
                try
                {
                    model.BirthDay = new DateTime(model.SetBirthDate.Year, model.SetBirthDate.Month, model.SetBirthDate.Day);
                }
                catch
                {
                    ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
                }

            }
            else if (model.SetBirthDate != null && (model.SetBirthDate.Day > 0 || model.SetBirthDate.Month > 0 || model.SetBirthDate.Year > 0))
            {
                ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
            }

            else
            {
                model.BirthDay = new DateTime(1900, 1, 1);
            }

            #endregion

            if (ModelState.IsValid)
            {
                var utmRefferal = "";
                //int id = (int)dbAccount.Insert(model.FirstName, model.LastName, model.Email, model.BirthDay, model.Address1, model.Address2, model.Address3, model.Address4, model.City, model.Phone, model.Mobile, model.Fax, model.PhoneInternational, model.Password, model.NewsLetter == true ? 1 : 0, model.CampaingSMSAndEmail == true ? 1 : 0);
                if (!string.IsNullOrEmpty(eStoreUser.UTMReferral))
                {
                    if (eStoreUser.UTMReferral == "akakce")
                    {
                        utmRefferal = "AA";
                    }
                    else if (eStoreUser.UTMReferral == "gittigidiyor")
                    {
                        utmRefferal = "GG";
                    }
                    else if (eStoreUser.UTMReferral == "cimri")
                    {
                        utmRefferal = "Cİ";
                    }
                    else if (eStoreUser.UTMReferral == "google")
                    {
                        utmRefferal = "GO";
                    }
                    else
                    {
                        utmRefferal = "";
                    }
                }

                int id = (int)dbAccount.Insert(model.FirstName, model.LastName, model.Email, model.BirthDay, "", "", "", "", 0, "", model.Mobile, "", "", model.Password, model.NewsLetter == true ? 1 : 0, model.CampaingSMSAndEmail == true ? 1 : 0, Parameters.Now, utmRefferal);

                if (id > 0)
                {
                    int productToAddCart = eStoreUser.ProductIdToAddCart;
                    string productVariantToAddCart = eStoreUser.ProductVariantToAddCart;
                    bool installmentSelected = eStoreUser.InstallmentSelected;
                    int productAmountToAddCart = eStoreUser.ProductAmountToAddCart;
                    string utmReferral = eStoreUser.UTMReferral ?? "";
                    int VisitorId = eStoreUser.AccountId;

                    //dbAddress.Insert(id, "Adresim", "", "", "", model.Address1, model.Address2, model.Address3, model.Address4, 1, model.City, id);
                    //dbAddress.Insert(id, "Fatura Adresim", "", "", "", model.Address1, model.Address2, model.Address3, model.Address4, 1, model.City, id);

                    Account account = dbAccount.Get(model.Email);

                    FormsAuthentication.SetAuthCookie(model.Email, false);

                    ActiveAccount activeAccount = new ActiveAccount();

                    activeAccount.AccountId = account.AccountId;
                    activeAccount.UserName = account.Email;
                    activeAccount.FirstName = account.FirstName;
                    activeAccount.LastName = account.LastName;
                    activeAccount.Email = account.Email;
                    activeAccount.Mobile = account.Mobile;
                    activeAccount.UTMReferral = utmReferral.ToUpperInvariant();
                    activeAccount.AccountType = 0;

                    #region Cart Summary

                    if (productToAddCart > 0)
                    {
                        if (Parameters.AllowVisitorsToUsingCart)
                        {
                            dbCart.VisitorToUser(VisitorId, activeAccount.AccountId);
                            dbAddress.VisitorToUser(VisitorId, activeAccount.AccountId);
                        }
                        else
                        {
                            dbCart.Insert(activeAccount.AccountId, 0, 0, productToAddCart, productAmountToAddCart, 0, false, installmentSelected, Parameters.Now, productVariantToAddCart, activeAccount.AccountType);
                        }
                    }

                    CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                    activeAccount.TotalQty = summary.TotalQty;
                    activeAccount.TotalPrice = summary.TotalPrice;
                    activeAccount.InstallmentPrice = summary.InstallmentPrice;
                    activeAccount.InstallmentTax = summary.InstallmentTax;

                    #endregion
                    activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                    ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();
                    Session["eStoreUser"] = activeAccount;

                    #region Verify Account Mail Send

                    string mailBody = dbRefs.GetRef5(200);
                    string Link = Parameters.WebSiteUrl + "/Account/Verify/?id=" + HttpUtility.UrlEncode(Crypt.Encrypt(activeAccount.Email));

                    Link = "<a href=\"" + Link + "\">" + Link + "</a>";
                    mailBody = mailBody.Replace("{Link}", Link).Replace("{FirstName}", activeAccount.FirstName).Replace("{LastName}", activeAccount.LastName).Replace("{Email}", activeAccount.UserName);

                    try
                    {
                        Utils.SendMail(activeAccount.Email, "", Parameters.NewMemberMailBccAddress, "Yeni Üye", mailBody, true);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }

                    #endregion

                    if (!string.IsNullOrEmpty(activeAccount.RedirectUrl))
                    {
                        return Json(new { url = activeAccount.RedirectUrl });
                    }
                    else if (productToAddCart > 0)
                    {
                        return Json(new { url = Parameters.WebSiteUrl + "/Cart/Index" });
                    }
                    else if (Parameters.UseWishList)
                    {
                        return Json(new { url = Parameters.WebSiteUrl + "/Contact/Index" });
                    }
                    else
                    {
                        return Json(new { url = Parameters.WebSiteUrl + "/Home/Index" });
                    }
                }
                else if (id == -1)
                {
                    ModelState.AddModelError("", "Sistemimizde Eposta adresi bulunmaktadır.");
                }
            }

            model.CityList = dbCity.GetList(1);
            return View(model);
        }

        #endregion

        #region Verify

        [AllowAnonymous]
        public ActionResult Verify(string id)
        {
            if (id != "")
            {
                try
                {
                    id = Crypt.Decrypt(id);
                }
                catch
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            int sonuc = dbAccount.Verify(id);
            if (sonuc == 0)
            {
                return RedirectToAction("Verified", "Account");
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        #endregion

        #region Verified

        [AllowAnonymous]
        public ActionResult Verified()
        {
            return View();
        }

        #endregion

        #region Edit Account

        public ActionResult Edit()
        {

          
            if (eStoreUser.AccountId > 0)
            {
                AccountEditModel model = new AccountEditModel();
                model.SetBirthDate = new DatePartsModel();
                AccountEdit accountEdit = new AccountEdit();

                Mapper.MapDomainToViewModel2(dbAccount.Get(eStoreUser.UserName), accountEdit);

                Mapper.MapDomainToViewModel2(accountEdit, model);

                if (model.BirthDay != new DateTime(1900, 1, 1))
                {
                    model.SetBirthDate.Day = model.BirthDay.Day;
                    model.SetBirthDate.Month = model.BirthDay.Month;
                    model.SetBirthDate.Year = model.BirthDay.Year;
                }
                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult Edit(AccountEditModel model)
        {
            #region Birthday Control

            if (model.SetBirthDate.Day > 0 && model.SetBirthDate.Month > 0 && model.SetBirthDate.Year > 0)
            {
                try
                {
                    model.BirthDay = new DateTime(model.SetBirthDate.Year, model.SetBirthDate.Month, model.SetBirthDate.Day);
                }
                catch
                {
                    ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
                }

            }
            else if (model.SetBirthDate.Day > 0 || model.SetBirthDate.Month > 0 || model.SetBirthDate.Year > 0)
            {
                ModelState.AddModelError("Birthday", "Doğum tarihi bilgisini kontrol ediniz.");
            }
            else
            {
                model.BirthDay = new DateTime(1900, 1, 1);
            }

            #endregion

            if (ModelState.IsValid)
            {
                dbAccount.Update(eStoreUser.UserName, model.FirstName, model.LastName, model.Email, model.BirthDay, model.Phone, model.Mobile, model.Fax, model.PhoneInternational);

                eStoreUser.FirstName = model.FirstName;
                eStoreUser.LastName = model.LastName;
                eStoreUser.Email = model.Email;

                if (eStoreUser.UserName != model.Email)
                {
                    FormsAuthentication.SignOut();
                    FormsAuthentication.SetAuthCookie(model.Email, createPersistentCookie: false);
                    eStoreUser.UserName = model.Email;
                }
                Session["eStoreUser"] = eStoreUser;
                return RedirectToAction("Index", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #endregion

        #region Change Password

        public ActionResult ChangePassword()
        {
         
            return View();
        }

        [CaptchaVerify("Hatalı Kod")]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {

         
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded = false;
                bool oldPasswordValid = false;

                try
                {
                    oldPasswordValid = dbAccount.CheckPassword(eStoreUser.UserName, model.OldPassword);

                    if (!oldPasswordValid)
                    {
                        ModelState.AddModelError("", "Eski şifreniz hatalı tekrar deneyiniz.");
                    }
                    else
                    {
                        changePasswordSucceeded = dbAccount.ChangePassword(eStoreUser.UserName, model.NewPassword);
                    }
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
          
            return View();
        }

        #endregion

        #region Remind Password

        [AllowAnonymous]
        public ActionResult RemindPassword()
        {

         
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult RemindPassword(RemindPasswordModel model)
        {

         
            string newPass = "";
            if (ModelState.IsValid)
            {
                bool remindPasswordSucceeded = false;

                try
                {
                    newPass = dbAccount.ResetPassword(model.UserName);
                    if (newPass != "Kullanıcı Bulunamadı!")
                    {
                        if (dbAccount.ChangePassword(model.UserName, newPass))
                        {
                            remindPasswordSucceeded = true;
                        }
                        else
                        {
                            remindPasswordSucceeded = false;
                        }
                    }
                    else
                    {
                        remindPasswordSucceeded = false;
                    }

                }
                catch (Exception)
                {
                    remindPasswordSucceeded = false;
                }

                if (remindPasswordSucceeded)
                {
                    model.Message = "<font color=green>Yeni şifreniz e-posta adresinize gönderilmiştir.</font>";
                    try
                    {
                        Account account = dbAccount.Get(model.UserName);
                        Utils.SendMail(model.UserName, "", "", "Şifre Hatırlatma", dbRefs.GetRef5(205).Replace("{FirstName}", account.FirstName).Replace("{LastName}", account.LastName).Replace("{Password}", newPass), true);
                    }
                    catch
                    {
                        model.Message = "<font color=red>Eposta gönderimi sırasında beklenmeyen bir hata oluştu. Bir süre sonra tekrar deneyiniz.</font>";
                    }
                }
                else
                {
                    model.Message = "<font color=red>Kullanıcı bulunamadı.</font>";
                }
            }

            return View(model);
        }

        #endregion

        #region GetErrorsFromModelState

        private IEnumerable<string> GetErrorsFromModelState()
        {
            return ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage));
        }

        #endregion

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        #region GenerateNewPassword

        public string GenerateNewPassword(int size)
        {
            char[] cr = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
            string result = string.Empty;
            Random r = new Random();
            for (int i = 0; i < size; i++)
            {
                result += cr[r.Next(0, cr.Length - 1)].ToString();
            }
            return result;
        }

        #endregion

        #region Guarantors

        public ActionResult Guarantors()
        {
          
            if (!Parameters.UsePaymentBond)
            {
                return Redirect("/Account/Index");
            }
            return View();
        }

        public ActionResult GuarantorsGet()
        {
            GuarantorsModel data = new GuarantorsModel();
            data.Guarantors = dbAccount.GetGuarantorList(eStoreUser.AccountId);
            data.AccountId = eStoreUser.AccountId;
            return View(data);
        }

        [AllowAnonymous]
        public ActionResult UpdateGuarantor(Guarantor gu, int? Id2)
        {
            if (Id2.HasValue)
            {
                GuarantorModel gm = new GuarantorModel();
                Guarantor g = new Guarantor();
                if (Id2 == 0)
                {
                    g.AccountId = 0;
                }
                else
                {
                    if (eStoreUser.AccountType == 0)
                    {
                        g = dbAccount.GetGuarantor((int)Id2);
                    }
                    else
                    {
                        g = dbAccount.GetVisitorGuarantor((int)Id2);
                    }
                }
                Mapper.MapDomainToViewModel(g, gm);
                gm.CityList = dbCity.GetList(1);
                if (gm.DogumTarihi.Year.ToString() != "1")
                {
                    gm.BirthDayNumber = gm.DogumTarihi.Day.ToString();
                    gm.BirthMonth = gm.DogumTarihi.Month.ToString();
                    gm.BirthYear = gm.DogumTarihi.Year.ToString();
                }

                gm.days = new List<SelectListItem>();
                gm.months = new List<SelectListItem>();
                gm.years = new List<SelectListItem>();

                var dayValue = "";
                gm.days.Add(new SelectListItem { Text = "Seçiniz", Value = "" });
                for (var i = 1; i <= 31; i++)
                {
                    dayValue = (i < 10) ? "0" + i.ToString() : i.ToString();
                    gm.days.Add(new SelectListItem { Text = dayValue, Value = i.ToString() });
                }

                gm.months.Add(new SelectListItem { Text = "Seçiniz", Value = "" });
                gm.months.Add(new SelectListItem { Text = "Ocak", Value = "1" });
                gm.months.Add(new SelectListItem { Text = "Şubat", Value = "2" });
                gm.months.Add(new SelectListItem { Text = "Mart", Value = "3" });
                gm.months.Add(new SelectListItem { Text = "Nisan", Value = "4" });
                gm.months.Add(new SelectListItem { Text = "Mayıs", Value = "5" });
                gm.months.Add(new SelectListItem { Text = "Haziran", Value = "6" });
                gm.months.Add(new SelectListItem { Text = "Temmuz", Value = "7" });
                gm.months.Add(new SelectListItem { Text = "Ağustos", Value = "8" });
                gm.months.Add(new SelectListItem { Text = "Eylül", Value = "9" });
                gm.months.Add(new SelectListItem { Text = "Ekim", Value = "10" });
                gm.months.Add(new SelectListItem { Text = "Kasım", Value = "11" });
                gm.months.Add(new SelectListItem { Text = "Aralık", Value = "12" });

                var eighteenAgo = DateTime.Now.Year - 18;
                var hundredAgo = DateTime.Now.Year - 100;
                gm.years.Add(new SelectListItem { Text = "Seçiniz", Value = "" });
                for (var i = eighteenAgo; i >= hundredAgo; i--)
                {
                    gm.years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
                }


                return PartialView("UpdateGuarantor", gm);
            }
            else
            {
                if (string.IsNullOrEmpty(gu.Anne_Ad) || string.IsNullOrEmpty(gu.Baba_Ad) || string.IsNullOrEmpty(gu.BirthDayNumber) || string.IsNullOrEmpty(gu.BirthMonth) || string.IsNullOrEmpty(gu.BirthYear)
                    || string.IsNullOrEmpty(gu.CepTel) || string.IsNullOrEmpty(gu.Cinsiyet) || string.IsNullOrEmpty(gu.DogumYer) || string.IsNullOrEmpty(gu.EvAdres)
                     || string.IsNullOrEmpty(gu.EvTel) || string.IsNullOrEmpty(gu.FirstName) || string.IsNullOrEmpty(gu.LastName) || string.IsNullOrEmpty(gu.IsGorev)
                     || string.IsNullOrEmpty(gu.IsYeriAdi) || string.IsNullOrEmpty(gu.N_AileSiraNo) || string.IsNullOrEmpty(gu.N_CiltNo)
                     || string.IsNullOrEmpty(gu.N_Cuzdan_No) || string.IsNullOrEmpty(gu.N_Ilce) || string.IsNullOrEmpty(gu.N_KutukIl) || string.IsNullOrEmpty(gu.N_Mahalle) || string.IsNullOrEmpty(gu.N_SeriNo)
                     || string.IsNullOrEmpty(gu.N_TCKimlikNo))
                {
                    return JavaScript("kefilEklenemedi('Lütfen gerekli alanları doldurun.');");
                }
                else if (!TCKimlikMod(gu.N_TCKimlikNo))
                {
                    return JavaScript("kefilEklenemedi('Geçerli bir TC Kimlik numarası girilmemiş.');");
                }
                gu.BirthDayNumber = Convert.ToInt32(gu.BirthDayNumber) < 10 ? "0" + gu.BirthDayNumber : gu.BirthDayNumber;
                gu.BirthMonth = Convert.ToInt32(gu.BirthMonth) < 10 ? "0" + gu.BirthMonth : gu.BirthMonth;
                string date = gu.BirthYear + "-" + gu.BirthMonth + "-" + gu.BirthDayNumber;
                string time = "00:00:00";
                gu.DogumTarihi = DateTime.ParseExact(date + " " + time, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                int result = 0;
                if (eStoreUser.AccountType == 0)
                {
                    result = dbAccount.InsertGuarantors(eStoreUser.AccountId, gu);
                }
                else
                {
                    result = dbAccount.InsertVisitorGuarantors(eStoreUser.AccountId, gu);
                }
                if (result > 0)
                {
                    return JavaScript("kefilEklendi();");
                }
                else
                {
                    return JavaScript("kefilEklenemedi('Kefil ekleme işlemi sırasında bir hata oluştu.');");
                }
            }
        }

        #endregion

    }
}
